package br.com.foxinline.manager.acao;

import br.com.foxinline.modelo.Imovel;
import br.com.foxinline.modelo.Registro;
import br.com.foxinline.modelo.TipoAtoImovel;
import br.com.foxinline.servico.ImovelServico;
import br.com.foxinline.servico.TipoAtoImovelServico;
import br.com.foxinline.utilitario.Mensagem;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author cadomeireles
 */
@ViewScoped
@ManagedBean
public class ManagerRegistroImovel implements Serializable {

    @EJB
    ImovelServico imovelServico;
    
    @EJB
    TipoAtoImovelServico atoImovelServico;
    
    private Imovel imovel;
    
    private Registro registro;
    
    private String imovelId;

    @PostConstruct
    public void init() {
        Map<String, String> parametros = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        this.imovelId = parametros.get("imovelId");

        if (imovelId != null) {
            this.imovel = imovelServico.pesquisar(Long.parseLong(imovelId));
        }

        this.registro = new Registro();

        Integer ultimoRegistro = imovelServico.obterUltimoNumeroRegistro(this.imovel);

        Integer ultimoAverbacao = imovelServico.obterUltimoNumeroAverbacao(this.imovel);
        
        this.registro.setNumero((ultimoRegistro > ultimoAverbacao ? ultimoRegistro : ultimoAverbacao) + 1);
    }

    public void registrar() {
        this.imovel.getRegistros().add(this.registro);
        imovelServico.atualizar(this.imovel);
        init();

        Mensagem.messagemInfo("Registro realizado com sucesso!");
    }

    public List<TipoAtoImovel> autocompletarTipoAtoImovel(String query) {
        return  atoImovelServico.autocompletarRegistros(query);
    }    
    
    public Imovel getImovel() {
        return imovel;
    }

    public void setImovel(Imovel imovel) {
        this.imovel = imovel;
    }

    public Registro getRegistro() {
        return registro;
    }

    public void setRegistro(Registro registro) {
        this.registro = registro;
    }
}
